﻿using CLCommuModbus;
using NationalInstruments.TestStand.Interop.API;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using IniParser.Model;
using IniParser;

namespace CLVisionCommu
{
    public partial class CLVisionCommuCaller
    {
        public static void WriteObjectStructToTS(JObject jb, PropertyObject strucVar, out int ErrorCode, out string ErrorText)
        {
            ErrorCode = 0;
            ErrorText = "NoError";
            try
            {
                foreach (var item in jb)
                {
                    bool canValid;
                    PropertyObject currentStrucVar;
                    if (item.Key.ToLower() != "root")
                    {

                        //判断是否可以创建层级
                        strucVar.ValidateNewSubPropertyName(item.Key, false, out canValid);
                        if (canValid)
                        {
                            //TS中创建新的子级
                            strucVar.NewSubProperty(item.Key, PropertyValueTypes.PropValType_Container, false, "", 0);
                        }
                        currentStrucVar = strucVar.GetPropertyObject(item.Key, 0);
                    }
                    else
                    {
                        currentStrucVar = strucVar;
                    }
                    JObject jbitem = JsonConvert.DeserializeObject(item.Value.ToString()) as JObject;

                    //遍历子节点Object
                    foreach (var item2 in jbitem)
                    {
                        string objectName = "";
                        int objectID = -1;

                        JObject jbitem1 = JsonConvert.DeserializeObject(item2.Value.ToString()) as JObject;
                        //Object具体内容

                        objectID = (int)jbitem1.Property("id").Value;
                        objectName = jbitem1.Property("name").Value.ToString();
                        string IDName = "ID" + objectID + "_" + objectName;
                        //判断是否可以创建层级
                        currentStrucVar.ValidateNewSubPropertyName(IDName, false, out canValid);
                        if (canValid)
                        {
                            //TS中创建新的子级
                            currentStrucVar.NewSubProperty(IDName, PropertyValueTypes.PropValType_Container, false, "", 0);
                        }
                        PropertyObject currentStrucVar1 = currentStrucVar.GetPropertyObject(IDName, 0);

                        foreach (var itemObj in jbitem1)
                        {
                            //含"#"的为多国语言参数,不显示在TS中
                            if (itemObj.Key.Contains("#"))
                            {
                                continue;
                            }
                            if (itemObj.Key.ToLower() == "id")
                            {
                                // objectID = Convert.ToInt32(itemObj.Value);

                            }
                            else if (itemObj.Key.ToLower() == "name")
                            {
                                //objectName = itemObj.Value.ToString();
                            }

                            else  //存储数据层
                            {



                                //判断是否可以创建层级
                                currentStrucVar1.ValidateNewSubPropertyName(itemObj.Key, false, out bool canValid_Input2);
                                if (canValid_Input2)
                                {
                                    //TS中创建新的子级
                                    currentStrucVar1.NewSubProperty(itemObj.Key, PropertyValueTypes.PropValType_Container, false, "", 0);
                                }
                                PropertyObject currentStrucVar2 = currentStrucVar1.GetPropertyObject(itemObj.Key, 0);
                                JObject jbProperty = JsonConvert.DeserializeObject(itemObj.Value.ToString()) as JObject;

                                string dataType = "";
                                bool isArray = false;
                                dataType = jbProperty.Property("dataType").Value.ToString();
                                isArray = (bool)jbProperty.Property("isArray");


                                foreach (var item3 in jbProperty)
                                {
                                    //含"#"的为多国语言参数,不显示在TS中
                                    if (item3.Key.Contains("#"))
                                    {
                                        continue;
                                    }
                                    //数据类型
                                    if (item3.Key.ToLower() == "datatype")
                                    {
                                        // dataType = item3.Value.ToString().ToUpper();
                                    }
                                    //数据是否为数组 
                                    else if (item3.Key.ToLower() == "isArray")
                                    {
                                        //isArray = Convert.ToInt32(item3.Value) == 1 ? true : false;
                                    }
                                    else if (item3.Key.ToLower() == "arraylength")
                                    {

                                        /* 暂未未找到直接修改节点数据类型的方法，如可以修改数据类型，则直接第3步，再修改数据类型  */
                                        //1、获取父节点
                                        PropertyObject propertyObject_str = currentStrucVar2.Parent;
                                        string proName = currentStrucVar2.Name;
                                        //2、删除指定的containter子节点
                                        propertyObject_str.DeleteSubProperty(proName, 0);
                                        //3、重新创建指定数据类型子节点
                                        PropertyValueTypes propertyValueType = PropertyValueTypes.PropValType_Container;

                                        DataType type = (DataType)Enum.Parse(typeof(DataType), dataType.ToUpper());
                                        switch (type)
                                        {
                                            case DataType.USHORT:
                                                propertyValueType = PropertyValueTypes.PropValType_Number;
                                                break;
                                            case DataType.INT:
                                                propertyValueType = PropertyValueTypes.PropValType_Number;
                                                break;
                                            case DataType.FLOAT:
                                                propertyValueType = PropertyValueTypes.PropValType_Number;
                                                break;
                                            case DataType.DOUBLE:
                                                propertyValueType = PropertyValueTypes.PropValType_Number;
                                                break;
                                            case DataType.STRING:
                                                propertyValueType = PropertyValueTypes.PropValType_String;
                                                break;
                                            default:
                                                break;
                                        }
                                        if (isArray)
                                        {
                                            propertyObject_str.NewSubProperty(proName, propertyValueType, true, "", 0);
                                            PropertyObject current = propertyObject_str.GetPropertyObject(proName, 0);

                                            //设置数组长度
                                            current.SetNumElements(System.Convert.ToInt32(item3.Value));
                                        }
                                        else
                                        {
                                            propertyObject_str.NewSubProperty(proName, propertyValueType, false, "", 0);
                                        }
                                    }
                                    else
                                    {

                                    }
                                }

                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorCode = -1;
                ErrorText = "向TestStand中写入Object数据失败！" + ex.Message;
            }
        }
        private static bool CreateObjectStructInTS(int threadCount, PropertyObject arrayContainerToReceiveConfig, string objectConfigFilePath, out int ErrorCode, out string ErrorText)
        {
            ErrorCode = 0;
            ErrorText = "NoError";
            try
            {
                string str = ReadFile(objectConfigFilePath, out ErrorCode, out ErrorText);
                //读取自定义参数
                JObject jb_Object = JsonConvert.DeserializeObject(str) as JObject;

                arrayContainerToReceiveConfig.DeleteElements(0, arrayContainerToReceiveConfig.GetNumElements());

                arrayContainerToReceiveConfig.SetNumElements(threadCount, 0);

                for (int i = 0; i < threadCount; i++)
                {
                    //获取数组元素
                    PropertyObject propertyElement = arrayContainerToReceiveConfig.GetPropertyObjectByOffset(i, 0);
                    //设置名称
                    // propertyElement.Name = "Thread" + i.ToString();
                    //将本地参数写入TS
                    WriteObjectStructToTS(jb_Object, propertyElement, out ErrorCode, out ErrorText);
                }
                return true;
            }
            catch (Exception ex)
            {
                ErrorCode = -1;
                ErrorText = "在TestStand中创建Object变量失败！" + ex.Message;
                throw;
            }
        }
        public static string ReadFile(string filePath, out int ErrorCode, out string ErrorText)
        {
            ErrorCode = 0;
            ErrorText = "NoError";
            string result = null;
            try
            {
                using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    using (StreamReader streamReader = new StreamReader(fs, Encoding.GetEncoding("GB2312")))
                    {
                        result = streamReader.ReadToEnd();
                    }
                }
                return result;
            }
            catch (Exception ex)
            {
                ErrorCode = -1;
                ErrorText = "读取本地文件失败！" + ex.Message;
                return result;
            }
        }
        public static string ReadIniFile(string configFilePath, string sectionName, string key, out int ErrorCode, out string ErrorText)
        {
            ErrorCode = 0;
            ErrorText = "NoError";
            try
            {
                // 使用FileIniDataParser实例解析或保存ini文件。
                var parser = new FileIniDataParser();

                // 加载INI文件，读取实例中包含的数据，并解析该数据
                IniData data = parser.ReadFile(configFilePath);
                return data[sectionName][key];
            }
            catch (Exception ex)
            {
                ErrorCode = -1;
                ErrorText = "读取ini参数文件失败！" + ex.Message;
                return null;
            }
        }
    }
}
